package com.sopt.friends.util;

import java.io.InputStream;
import java.sql.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.google.android.maps.MyLocationOverlay;
import com.sopt.friends.db.FriendsDBHelper;
import com.sopt.friends.db.Constants.FriendsDB;
import com.sopt.friends.statics.FriendsStaticVars;
import com.sopt.friends.vo.FriendsChat;
import com.sopt.friends.vo.FriendsChatRoom;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.widget.Toast;

public class FriendsChatManager {
	private Context c;
	private ContentResolver currentResolver;
	private SQLiteDatabase db;

	public FriendsChatManager(Context context, ContentResolver contentResolver) {
		this.c = context;
		this.currentResolver = contentResolver;
	}

	public SQLiteDatabase getDb() {
		return db;
	}

	public void setDb(SQLiteDatabase db) {
		this.db = db;
	}
	public String getMemberIdByNumber(String number){
		String curId = "";
		String[]columns = {FriendsDB.MEMBER_ID};
		String selection = FriendsDB.PHONE_NUMBER + " = ('"+number+"')";
		FriendsDBHelper dbhelper = new FriendsDBHelper(c);
		db = dbhelper.getReadableDatabase();
		Cursor cursor = db.query(FriendsDB.TABLE_PHONE, columns, selection, null, null, null, null);
		if(cursor.moveToNext())
			curId = cursor.getString(cursor.getColumnIndex(FriendsDB.MEMBER_ID));
		
		cursor.close();
		db.close();
		return curId;
	}

	public String[] getMyFriendsPhoneList() {
		ArrayList<String> list = new ArrayList<String>();
		FriendsDBHelper dbhelper = new FriendsDBHelper(c);
		String[] columns = { FriendsDB.PHONE_NUMBER };
		db = dbhelper.getReadableDatabase();
		Cursor cursor = db.query(FriendsDB.TABLE_PHONE, columns, null, null,
				null, null, null);

		while (cursor.moveToNext()) {
			String curNum = cursor.getString(cursor
					.getColumnIndex(FriendsDB.PHONE_NUMBER));
			list.add(curNum);
		}
		
		cursor.close();
		
		for (int i = 0; i < list.size(); i++) {
			String[] colums2 = { FriendsDB.MEMBER_NAME };
			String where = FriendsDB.MEMBER_ID + " = ( select "
					+ FriendsDB.MEMBER_ID + " from " + FriendsDB.TABLE_PHONE
					+ " where " + FriendsDB.PHONE_NUMBER + " = '" + list.get(i)
					+ "')";
			cursor = db.query(FriendsDB.TABLE_MEMBER, colums2, where, null, null,
					null, null);
			String curName = list.get(i);
			if (cursor.moveToNext()) {
				curName = curName+"/"+cursor.getString(cursor
						.getColumnIndex(FriendsDB.MEMBER_NAME));
			}
			cursor.close();
			list.set(i,curName);
		}
		
		db.close();
		
		String[] arr = new String[list.size()];
		arr = list.toArray(arr);
		return arr;
	}

	public ArrayList<FriendsChatRoom> getChatRoomList() {
		ArrayList<FriendsChatRoom> list = new ArrayList<FriendsChatRoom>();

		FriendsDBHelper dbhelper = new FriendsDBHelper(c);

		String[] columns = { FriendsDB.PHONE_NUMBER };

		db = dbhelper.getReadableDatabase();
		Cursor cursor = db.query(FriendsDB.TABLE_CHAT, columns, null, null,
				null, null, null);

		ArrayList<String> numberList = new ArrayList<String>();
		
		while (cursor.moveToNext()) {
			String curNum = cursor.getString(cursor
					.getColumnIndex(FriendsDB.PHONE_NUMBER));
			if (!numberList.contains(curNum)) {
				numberList.add(curNum);
			}
		}
		cursor.close();
		for (int i = 0; i < numberList.size(); i++) {
			String curNum = numberList.get(i);
			String[] inColum = { "count(*) as count" };
			String where = FriendsDB.PHONE_NUMBER + " = ('" + curNum + "')";

			cursor = db.query(FriendsDB.TABLE_CHAT, inColum, where, null, null,
					null, null);

			if (cursor.moveToNext()) {
				FriendsChatRoom room = new FriendsChatRoom();
				room.setTargetnumber(curNum);
				room.setCountmessage(cursor.getString(cursor
						.getColumnIndex("count")));
				list.add(room);
			}
			cursor.close();
		}
		
		for (FriendsChatRoom curRoom:list) {
			String[] colums2 = { FriendsDB.MEMBER_NAME };
			String where = FriendsDB.MEMBER_ID + " = ( select "
					+ FriendsDB.MEMBER_ID + " from " + FriendsDB.TABLE_PHONE
					+ " where " + FriendsDB.PHONE_NUMBER + " = '" + curRoom.getTargetnumber()
					+ "')";
			cursor = db.query(FriendsDB.TABLE_MEMBER, colums2, where, null, null,
					null, null);
			
			if (cursor.moveToNext()) {
				curRoom.setTargetname(cursor.getString(cursor
						.getColumnIndex(FriendsDB.MEMBER_NAME)));
			}
			cursor.close();
			
		}
		
		for(FriendsChatRoom curRoom:list){
			String[] inColum = { FriendsDB.MEMBER_ID };
			String where = FriendsDB.PHONE_NUMBER + " = ('" + curRoom.getTargetnumber() + "')";

			cursor = db.query(FriendsDB.TABLE_PHONE, inColum, where, null, null,
					null, null);
			if(cursor.moveToNext()){
				Uri uri = ContentUris.withAppendedId(
						ContactsContract.Contacts.CONTENT_URI, Long
								.parseLong(cursor.getString(cursor.getColumnIndex(FriendsDB.MEMBER_ID))));
				InputStream is = ContactsContract.Contacts
						.openContactPhotoInputStream(currentResolver, uri);
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				
				curRoom.setImage(bitmap);
			}
			cursor.close();

		}
		db.close();

		return list;
	}
	
	public boolean insertChatNew(String targetNum, String content) {
		boolean result = false;
		
		FriendsDBHelper dbhelper = new FriendsDBHelper(c);

		db = dbhelper.getWritableDatabase();
		
		Calendar cal = Calendar.getInstance();
		String year = String.valueOf(cal.get(Calendar.YEAR));
		String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
		String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
		SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date dt = new Date();
		
		ContentValues values = new ContentValues();
		
		values.put(FriendsDB.PHONE_NUMBER, targetNum);
		values.put(FriendsDB.CHAT_CONTENT, content);
		values.put(FriendsDB.CHAT_REGDATE, adf.format(dt));
		values.put(FriendsDB.CHAT_MINE,FriendsStaticVars.CURRENT_USER_NUMBER);
		long rs = db.insert(FriendsDB.TABLE_CHAT, null, values);
		
		if(rs==-1){
			showToast("INSERT ERROR !");
			return false;
		}else{
			showToast("Saved");
			result = true;
		}

		db.close();
		return result;
	}

	public boolean createChatRoom(String targetNum) {
		boolean result = false;
		FriendsDBHelper dbhelper = new FriendsDBHelper(c);

		db = dbhelper.getWritableDatabase();
		
		Calendar cal = Calendar.getInstance();
		String year = String.valueOf(cal.get(Calendar.YEAR));
		String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
		String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
		SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date dt = new Date();
		
		ContentValues values = new ContentValues();
		
		values.put(FriendsDB.PHONE_NUMBER, targetNum);
		values.put(FriendsDB.CHAT_CONTENT, "Start Chat with " + targetNum);
		values.put(FriendsDB.CHAT_REGDATE, adf.format(dt));
		long rs = db.insert(FriendsDB.TABLE_CHAT, null, values);
		
		if(rs==-1){
			showToast("INSERT ERROR !");
			return false;
		}else{
			showToast("Saved");
			result = true;
		}

		db.close();
		return result;
	}
	
	public ArrayList<FriendsChat> getChatListByNumber(String targetnum){
		ArrayList<FriendsChat> list = new ArrayList<FriendsChat>();
		FriendsDBHelper dbhelper = new FriendsDBHelper(c);

		String[] columns = { FriendsDB.CHAT_REGDATE, FriendsDB.CHAT_CONTENT, FriendsDB.CHAT_MINE };
		String where = FriendsDB.PHONE_NUMBER + " = ('" + targetnum +"')";
		String order = FriendsDB.CHAT_REGDATE +" DESC";
		db = dbhelper.getReadableDatabase(); 
		Cursor cursor = db.query(FriendsDB.TABLE_CHAT, columns, where, null,
				null, null, order);
		
		while(cursor.moveToNext()){
			FriendsChat curChat = new FriendsChat();
			curChat.setMine( cursor.getString(cursor.getColumnIndex(FriendsDB.CHAT_MINE)));
			curChat.setRegdate( cursor.getString(cursor.getColumnIndex(FriendsDB.CHAT_REGDATE)) );
			curChat.setContent( cursor.getString(cursor.getColumnIndex(FriendsDB.CHAT_CONTENT)) );
			curChat.setFrommembernum(targetnum);
			list.add(curChat);
		}
		
		cursor.close();
		db.close();
		return list;
	}
	
	
	public void showToast(String msg){
		Toast.makeText(c, msg, Toast.LENGTH_SHORT).show();
	}
	public void showToastLong(String msg){
		Toast.makeText(c, msg, Toast.LENGTH_LONG).show();
	}

}
